<template>
<view class="main-view">
	<view v-if="errmsg==''" class="content-view">
		<scroll-view scroll-y="true" style="height: calc(100vh - 42px);">
		<ly-tree
			node-key="id"
			expand-on-check-node
			show-checkbox 
			:tree-data="treeData" 
			:highlight-current="true" 
			:props="defaultProps"
			@check="handleCheck"
			@check-change="handleCheckChange"/>
		</scroll-view>	
		<view class="bottom-wrapper" >
			<view  style="display: flex;height: 100%;margin-bottom: 10px;justify-content: center;">
				<view @click="btnclick(0)"  style="margin-left: 5vw; width: 90vw; border-radius: 10px; align-items: center; display: flex;justify-content: center;height: 100%; background-color: #F55C23;color: #fff;">{{btns[0].text}}</view>
			</view>
		</view>
	</view>
	<view v-else class="error-view">
		{{errmsg}}
	</view>
</view>
</template>

<script>
var util = require("../../utils/util.js");
var infolistutil = require("../../utils/infolistutil.js");
import LyTree from '@/components/ly-tree/ly-tree.vue'
const app = getApp().globalData;
export default{
	components: {
		LyTree
	},
	data() {
		return {
			defaultProps: {
				children: 'children',
				label: 'label'
			},
			btns:[{
				"name": "save",
				"text": "保存",
				"type": "save",
				"visible": true,
				"btnToDo": "save",
				"clicked": {},
				"position": "pagebottom",
				"powerModId": "1880",
				"powerModCode": "ESM6510"
			}],
			errmsg:'',
			headerList:[],
			datalist:[],
			rstlist:[],
			datalisttemp:[],
			marginheight:800,
			pageName:'',
			templetName:'',
			modid:'',
			menuid:'',
			ismask:false,
			layerheight:0,
			layerheightmargin:0,
			clientHeight:0,
			layercontent:{},
			conditions:{},
			conditionsname:'',
			div:[],
			datastyle:[],
			rowClickDynamic:{},
			rowClick:'',
			isloadmore:true,
			dataObject:'',
			divArea:'',
			divstyle:{},
			treeData:[],
			colNames:[],
			baseKey:'',
			isrequest:true,
			headbtns:[{'backgroundcolor':'#fff','color':'#333','colvalue':'重置','opttype':'cz'},{'backgroundcolor':'#f00','color':'#fff','colvalue':'确认','opttype':'qr'}]
		}
	},
	
	onLoad:function(options){
		var that = this
		console.log(options)
		uni.hideHomeButton()
		var productCode = uni.getStorageSync('productCode')
		var sessionId = uni.getStorageSync('sessionId')
		var projectCode = uni.getStorageSync('projectCode')
		var terminaltype = uni.getStorageSync('terminaltype')
		var dbId = uni.getStorageSync('dbId')
		var userId = uni.getStorageSync('userId')
		var userName = uni.getStorageSync('userName')
		var pageName = options.pagename
		var templetName = options.templatename
		var modid = options.modid
		var menuid = options.menuid
		var conditions = options.conditions==undefined ? {} : JSON.parse(options.conditions)
		that.pageName = pageName
		that.templetName = templetName
		that.modid = modid
		that.menuid  = menuid
		uni.setNavigationBarTitle({title:options.menuname})
		var injson = '{"productCode":"' + productCode + '","terminalType":"' + terminaltype + '","projectCode":"' +
			projectCode + '","dbId":"' + dbId + '","templetName":"' + templetName + '","pageName":"' + pageName +
			'","menuId":"'+menuid+'","modId":"' + modid + '","sessionId":"' + sessionId + '","userId":"' + userId +
			'","userName":"' + userName + '"}';
		console.log(injson)
		uni.showLoading({title: '加载中'})
		uni.request({
			url: getApp().globalData.app_address + '?method=saas_PageStyle&parse=json',
			data: injson,
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			success: function(res) {
				var result = res.data;
				console.log(result)
				
				var div = result.data.div
				that.div = div
				var datastyle = div[0].style.colStyle
				var divClass = div[0].divClass
				that.rowClick = div[0].style.rowClick
				that.rowClickDynamic = div[0].style.rowClickDynamic
				that.datastyle = datastyle
				var divArea = div[0].name
				var dataObject = div[0].style.dataObject
				that.dataObject = dataObject
				that.divArea = divArea
				var pageConditions = {}
				pageConditions['pageNumber'] = 1
				pageConditions['rowsPerPage'] = 5
				pageConditions['isAllData'] = false
				that.pageConditions = pageConditions
				var temconditions = {}
				if(div[0].style.conditions != undefined){
					temconditions[divArea] = conditions
					that.conditions = temconditions
				}
				var replaceConditions = {}
				var replaceColumns = div[0].style.replaceColumns
				if(JSON.stringify(replaceColumns) != '[]'){
					for(var q=0; q<replaceColumns.length; q++){
						var type = replaceColumns[q].type
						if(type == 'column'){
							var colName= replaceColumns[q].column.colName
							replaceConditions[replaceColumns[q].toReplace] = conditions[colName]
						}
						if(type == 'value'){
							var replaceValue = replaceColumns[q].value
							if(replaceValue == "#PROJECTCODE#"){
								replaceConditions[replaceColumns[q].toReplace] = uni.getStorageSync('projectCode')
							}
						}
					}
				}
				
				
				var injson2 = '{"productCode":"' + productCode + '","terminalType":"' + terminaltype + '","projectCode":"' +
					projectCode + '","dbId":"' + dbId + '","templetName":"' + templetName + '","pageName":"' + pageName +
					'","menuId":"'+menuid+'","modId":"' + modid + '","sessionId":"' + sessionId + '","userId":"' + userId +
					'","userName":"' + userName + '","divArea":"' + divArea + '","dataObject":"' + dataObject + 
					'" ,"conditions":' + JSON.stringify(temconditions) + ',"replaceConditions":' + JSON.stringify(replaceConditions) + ',"pageConditions":' + JSON.stringify(pageConditions) + '}';
				console.log(injson2)
				uni.request({
					url: getApp().globalData.app_address + '?method=saas_PageDivData&parse=json',
					data: injson2,
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						var result = res.data;
						console.log(result)
						var datalisttemp = JSON.parse(JSON.stringify( result.data.div.value))
						var roleid = ''
						var userid = ''
						try{
							var baseKey = div[1].style.initialValues[0].foreignKeyArr[0].baseKey
							if(baseKey == 'roleid'){
								
							}else if(baseKey == 'userid'){
								userid = userId
								roleid = ' '
							}
						}catch(e){}
						that.treeData = util.parseTree(datalisttemp,roleid, userid)
						that.datalist = datalisttemp
						
						console.log(that.treeData)
						uni.hideLoading()
					},
				})
				
				
				var datastyle = div[1].style.colStyle
				var colNames = div[1].style.colNames
				
				that.colNames = colNames
				
				var divClass = div[1].divClass
				var divArea = div[1].name
				var dataObject = div[1].style.dataObject
				var pageConditions = {}
				pageConditions['pageNumber'] = 1
				pageConditions['rowsPerPage'] = 5
				pageConditions['isAllData'] = true
				var temconditions = {}
				temconditions[divArea] = conditions
				
				var replaceConditions = {}
				var replaceColumns = div[1].style.replaceColumns
				if(JSON.stringify(replaceColumns) != '[]'){
					for(var q=0; q<replaceColumns.length; q++){
						var type = replaceColumns[q].type
						if(type == 'column'){
							var colName= replaceColumns[q].column.colName
							replaceConditions[replaceColumns[q].toReplace] = conditions[colName]
						}
						if(type == 'value'){
							var replaceValue = replaceColumns[q].value
							if(replaceValue == "#PROJECTCODE#"){
								replaceConditions[replaceColumns[q].toReplace] = uni.getStorageSync('projectCode')
							}
						}
					}
				}
				var injson2 = '{"productCode":"' + productCode + '","terminalType":"' + terminaltype + '","projectCode":"' +
					projectCode + '","dbId":"' + dbId + '","templetName":"' + templetName + '","pageName":"' + pageName +
					'","menuId":"'+menuid+'","modId":"' + modid + '","sessionId":"' + sessionId + '","userId":"' + userId +
					'","userName":"' + userName + '","divArea":"' + divArea + '","dataObject":"' + dataObject + 
					'" ,"conditions":' + JSON.stringify(temconditions) + ',"replaceConditions":' + JSON.stringify(replaceConditions) + ',"pageConditions":' + JSON.stringify(pageConditions) + '}';
				console.log(injson2)
				uni.request({
					url: getApp().globalData.app_address + '?method=saas_PageDivData&parse=json',
					data: injson2,
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						var result = res.data;
						console.log(result)
						var rstlisttemp = result.data.div.value
						that.rstlist = rstlisttemp
						that.olddatalist = JSON.parse(JSON.stringify(that.rstlist))
					},
				})
			},
		})
	},
	 
	methods: {
		btnclick(index){
			var that = this
			var btns = that.btns
			var btntype = btns[index].name
			var btntext = btns[index].text
			var todo = btns[index].btnToDo
			var productCode = uni.getStorageSync('productCode')
			var sessionId = uni.getStorageSync('sessionId')
			var projectCode = uni.getStorageSync('projectCode')
			var terminaltype = uni.getStorageSync('terminaltype')
			var dbId = uni.getStorageSync('dbId')
			var userId = uni.getStorageSync('userId')
			var userName = uni.getStorageSync('userName')
			
			var injsondate = '{"productCode":"' + productCode + '","terminalType":"' + terminaltype + '","dbId":"' + dbId + '","sessionId":"' + sessionId + '"}';
			uni.request({
				url: getApp().globalData.app_address + '?method=getDate&parse=json',
				data: injsondate,
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				success: function(res) {
					console.log(res)
						var datestr = res.data.data.getDate
						console.log(datestr)
						var date = datestr.substring(0,19)
						if(todo == 'save' ){
							if((JSON.stringify(that.rstlist) == JSON.stringify(that.olddatalist))){
								uni.showModal({
								    title: '提示',
								    content: '没有要提交的数据',
									showCancel:false
								})
								return
							}
							
							if(that.isrequest){
								that.isrequest = false	
								var commitArr = []
								var dataList = that.rstlist
								var olddatalist = that.olddatalist
								var commitobj = {}
								var div = that.div
								commitobj['divArea'] =div[1].name
								commitobj['dataObject'] = div[1].style.dataObject
								var dataArr = []
								var dataobj = {}
								console.log(dataList)
								
								for(var i=0; i<dataList.length; i++){
									var type = dataList[i].opttype
									if(type == undefined){
										continue
									}
									dataobj['row'] = i
									dataobj['type'] = dataList[i].opttype
									dataobj['data'] = dataList[i]
									var log = {}
									var conditions = {}
									var colStyle2 = div[1].style.colStyle
									for(var g=0; g<colStyle2.length; g++){
										var itemstyle = colStyle2[g]
										if(itemstyle.style.key){
											conditions[itemstyle.name] = dataList[i][itemstyle.name]
										}
									}
									var modcode = dataList[i].modcode
									var newitem = dataList[i]
									var log = {}
									if(JSON.stringify(olddatalist) != '[]'){
										var opttype = dataList[i].opttype
										if(opttype == 'update'){
											for(var u=0;u<olddatalist.length;u++){
												var olditem = olddatalist[u]
												if(modcode == olditem.modcode){
													var colNames = that.colNames
													for(var n=0; n<colNames.length;n++){
														var obj = {}
														obj['nValue'] = newitem[colNames[n]]
														obj['oValue'] = olditem[colNames[n]]
														obj['title'] = colNames[n]
														log[colNames[n]] = obj
													}
													
												}
											}
										}else if(opttype == 'insert'){
											var colNames = that.colNames
											for(var n=0; n<colNames.length;n++){
												var obj = {}
												obj['nValue'] = newitem[colNames[n]]
												obj['oValue'] = ''
												obj['title'] = colNames[n]
												log[colNames[n]] = obj
											}
											
										}
										
									}else{
										var colNames = that.colNames
										for(var n=0; n<colNames.length;n++){
											var obj = {}
											obj['nValue'] = newitem[colNames[n]]
											obj['oValue'] = ''
											obj['title'] = colNames[n]
											log[colNames[n]] = obj
										}
									}
									
									dataobj['log'] = log
									dataobj['conditions'] = conditions
									dataArr.push(dataobj)
									commitobj['dataArr'] = dataArr
									
								}
								commitArr.push(commitobj)
								
								var pageName = that.pageName
								var templetName = that.templetName
								var modid = that.modid
								var menuid = that.menuid
								var injson = '{"productCode":"' + productCode + '","terminalType":"' + terminaltype + '","projectCode":"' +
									projectCode + '","dbId":"' + dbId + '","templetName":"' + templetName + '","pageName":"' + pageName +
									'","menuId":"'+menuid+'","modId":"' + modid + '","sessionId":"' + sessionId + '","userId":"' + userId +
									'","userName":"' + userName + '","btnName":"' + btntype + '","btnText":"' + btntext + '","commitArr":' + JSON.stringify(commitArr) + '}';
								console.log(injson)
								uni.showLoading({title: '加载中'})
								uni.request({
									url: getApp().globalData.app_address + '?method=saas_PageCommitData&parse=json',
									data: injson,
									method: 'POST',
									header: {'content-type': 'application/x-www-form-urlencoded'},
									success: function(res) {
										var result = res.data
										uni.hideLoading()
										console.log(result)
										if(result.rtn == 1){
											
											uni.showToast({title: '操作成功!',position:'bottom',icon:'none',duration: 1000 })
											setTimeout(function() {
												uni.navigateBack({delta: 1})
											}, 1000);
										}
									},
								})
								
							}
						}
					}
				})
		},
		
		handleCheck(obj) {
			// console.log('handleCheck', obj);
			var that = this
			var data = obj.node.data
			var children = data.children
			var datalist = JSON.parse(JSON.stringify(that.datalist)) 
			if(JSON.stringify(children) == '[]'){
				var funname = data.funname
				var checkednum = obj.node.checked ? '1' : '0'
				var modcode = data.modcode.substring(0, data.modcode.length-2)
				for(var i=0; i<datalist.length; i++){
					var itempre = datalist[i]
					var modcodepre = itempre.modcode
					if(modcode == modcodepre){
						for(var j=0;j<16;j++){
							var funnum = ''
							if(j>=9){
								funnum = '' + (j)
							}else{
								funnum = '0' + (j)
							}
							var funnamestr = 'funname' + funnum
							var funstr = 'fun' + funnum
							var funnamepre = itempre[funnamestr]
							if(funnamepre == funname){
								itempre[funstr] = checkednum
								var rtslist = that.rstlist
								if(checkednum == 1){
									if(JSON.stringify(rtslist) != '[]'){
										var ishave = false
										for(var m=0;m<rtslist.length;m++){
											var rtsitem =  rtslist[m]
											var rtsmodcode = rtsitem.modcode
											if(modcode == rtsmodcode){
												ishave = true
												rtsitem[funstr] = checkednum
												rtsitem['ismodify'] = true
												rtsitem['opttype'] = 'update'
												rtslist[m] = rtsitem
												that.rstlist = rtslist
												continue
											}
										}
										if(!ishave){
											var colNames = that.colNames
											var obj = {}
											for(var h=0; h<colNames.length; h++){
												obj[colNames[h]] = itempre[colNames[h]]
												obj['opttype'] = 'insert'
												rtslist.push(obj)
												that.rstlist = rtslist
											}
										}
									}else{
										var colNames = that.colNames
										var obj = {}
										for(var h=0; h<colNames.length; h++){
											obj[colNames[h]] = itempre[colNames[h]]
											obj['opttype'] = 'insert'
											rtslist.push(obj)
											that.rstlist = rtslist
										}
									}
								}else{
									var isallunselect = true
									for(var b=0;b<16;b++){
										var funnum2 = ''
										if(b>=9){
											funnum2 = '' + (b)
										}else{
											funnum2 = '0' + (b)
										}
										var funstr2 = 'fun' + funnum2
										var funnamestr2 = 'funname' + funnum2
										if(itempre[funstr2] == '1' && itempre[funnamestr2] != ''){
											isallunselect = false
										}
									}
									if(isallunselect){
										for(var m=0;m<rtslist.length;m++){
											var rtsitem =  rtslist[m]
											var rtsmodcode = rtsitem.modcode
											if(modcode == rtsmodcode){
												rtsitem[funstr] = checkednum
												rtsitem['ismodify'] = true
												rtsitem['opttype'] = 'delete'
												rtslist[m] = rtsitem
												that.rstlist = rtslist
												continue
											}
										}
									}else{
										for(var m=0;m<rtslist.length;m++){
											var rtsitem =  rtslist[m]
											var rtsmodcode = rtsitem.modcode
											if(modcode == rtsmodcode){
												rtsitem[funstr] = checkednum
												rtsitem['ismodify'] = true
												rtsitem['opttype'] = 'update'
												rtslist[m] = rtsitem
												that.rstlist = rtslist
												continue
											}
										}
									}
								}
								console.log(that.rstlist)
								continue
							}
						}
						
						datalist[i] = itempre
						that.datalist = datalist
						continue
					}
				}
				
				
			}
			else{
				var modname = data.modname
				var checkednum = obj.node.checked ? '1' : '0'
				var modcode = data.modcode
				for(var i=0; i<datalist.length; i++){
					var itempre = datalist[i]
					var modcodepre = itempre.modcode
					if(modcodepre.indexOf(modcode) != -1){
						var children = itempre.children
						if(JSON.stringify(children) != '[]'){
							for(var j=0;j<16;j++){
								var funnum = ''
								if(j>=9){
									funnum = '' + (j)
								}else{
									funnum = '0' + (j)
								}
								var funstr = 'fun' + funnum
								itempre[funstr] = checkednum
							}
							datalist[i] = itempre
							that.datalist = datalist
						}
						itempre['ismodify'] = true
						itempre.power = checkednum
						
						var rtslist = that.rstlist
						if(checkednum == '1'){
							if(JSON.stringify(rtslist) =='[]'){
								var colNames = that.colNames
								var obj = {}
								for(var h=0; h<colNames.length; h++){
									obj[colNames[h]] = itempre[colNames[h]]
								}
								obj['power'] = checkednum
								obj['opttype'] = 'insert'
								rtslist.push(obj)
								that.rstlist = rtslist
							}else{
								var ishave = false
								for(var h=0; h<rtslist.length; h++){
									var rtsitem = rtslist[h]
									var rtsmodcode = rtsitem.modcode
									if(rtsmodcode == modcodepre){
										ishave = true
										rtsitem['ismodify'] = true
										rtsitem['opttype'] = 'update'
										for(var j=0;j<16;j++){
											var funnum2 = ''
											if(j>=9){
												funnum2 = '' + (j)
											}else{
												funnum2 = '0' + (j)
											}
											var funstr2 = 'fun' + funnum2
											rtsitem[funstr2] = checkednum
											rtsitem['power'] = checkednum
										}
										rtslist[h] = rtsitem
										that.rstlist = rtslist
									}
								}
								if(!ishave){
									var colNames = that.colNames
									var obj = {}
									for(var h=0; h<colNames.length; h++){
										obj[colNames[h]] = itempre[colNames[h]]
									}
									obj['power'] = checkednum
									obj['opttype'] = 'insert'
									rtslist.push(obj)
									that.rstlist = rtslist
								}
							}
							
						}else{
							for(var h=0; h<rtslist.length; h++){
								var rtsitem = rtslist[h]
								var rtsmodcode = rtsitem.modcode
								if(rtsmodcode.indexOf(modcode) != -1){
									rtsitem['opttype'] = 'delete'
									rtsitem['ismodify'] = true
									rtslist[h] = rtsitem
									that.rstlist = rtslist
								}
							}
						}
						
						datalist[i] = itempre
					}
				}
				
				
				that.datalist = datalist
				console.log(that.rstlist)
			}
		},
		
		handleCheckChange(obj){
		},
		
	}
}
</script>

<style>
	.main-view{width: 100vw;height: 100vh;background-color: #f0f0f0;}
	.content-view{width: 100vw;height: 100vh;position:relative;}
	.error-view{display: flex;color: #aaa;justify-content: center;flex-direction: column;align-items: center;}
	.bottom-wrapper{background-color: #fff; height: 40px; width: 100vw;display: flex;flex-direction: row;justify-content: space-between;position: absolute;bottom: 0;align-items: center;z-index:200}
</style>